package com.pro.service;

import com.alibaba.fastjson.JSONObject;
import com.pro.config.ACloudConfig;
import com.pro.config.ServerConfig;
import com.pro.start.ServiceRenewal;
import com.pro.utils.HttpClientUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

/**
 * Copyright C 四川众鹏科技有限公司
 * All right reserved.  RegisterServiceS
 * 创建者：aoneng 2022/9/16
 * Description:
 * 备注   :
 * version:  V1.0
 * <author> - <version > - <time>  -    <desc>
 *
 * @author 敖能         V1.0       2022/9/16    完成基本功能
 */
public class RegisterClientService {
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ACloudConfig aCloudConfig;
    @Autowired
    private ServiceRenewal serviceRenewal;
    @Autowired
    private Environment env;
    private static final Log log = LogFactory.getLog(RegisterClientService.class);

    /**
     * 注册服务
     */
    public void register(){
        log.info("服务注册开始：" );
        JSONObject jobj= requestParameter();
        while (true){
            JSONObject result = HttpClientUtils.httpPost(aCloudConfig.getServerRegisterUrl() + "/aCloud/register", jobj);
            log.info("服务注册结果：" + result);
            if (result != null && result.getInteger("code") == 200) {//注册成功
                log.info("服务注册成功" );
                //服务续约请求
                serviceRenewal.serviceRenewalStart();
                return;
            }
            //注册失败一直重试
        }
    }
    /**
     * 服务续约
     */
    public void renewal(){
        log.info("服务续约开始：" );
        JSONObject jobj= requestParameter();
        //续约时长
        jobj.put("renewalDuration", 5000L);
        while (true){
            JSONObject result = HttpClientUtils.httpPost(aCloudConfig.getServerRegisterUrl() + "/aCloud/renewal", jobj);
            log.info("服务续约结果：" + result);
            if (result != null && result.getInteger("code") == 200) {//注册成功
                log.info("服务续约成功" );
                return;
            }
            //注册失败一直重试
        }
    }

    /**
     * 获取服务名称和地址
     * @return
     */
    public JSONObject requestParameter() {
        // 1.获取ip和端口号码
        String appHostAndPort = serverConfig.getAppHostAndPort();
        // 2. sericeName 服务的名称
        String serviceName = env.getProperty("spring.application.name");
        //3.注册中心url地址
        String serverRegisterUrl = aCloudConfig.getServerRegisterUrl();
        JSONObject data = new JSONObject();
        data.put("serviceName", serviceName);
        data.put("serviceAddres", appHostAndPort);
        return data;
    }
}
